<?php

namespace App\Admin\Repositories\Common;

use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\Repository;
use Carbon\Carbon;
use App\Admin\Controllers\Common\SelectorArray;
use App\Admin\Controllers\Common\DataSource;
use App\Admin\Controllers\Common\ColumnArray;

class CommonGridLatitude extends Repository
{
	protected $board = '';
	public function __construct($board) {
		$this->board = $board;
	}

	public function get(Grid\Model $model)
	{
		$arr = [];
		# 获取数据筛选条件
		// 日期
		$beginDate = $model->filter()->input('between.start') ?? date('Y-m-d', strtotime('-6 days'));
        $endDate = $model->filter()->input('between.end') ?? date('Y-m-d', time());
        if ($model->filter()->input('date')) {
            $beginDate = $model->filter()->input('date');
            $endDate = $model->filter()->input('date');
        }
        // 维度
        $lat1 = $model->filter()->input('_selector.latitude1') ?? array_keys(ColumnArray::$latitudeArr[$this->board]['select'])[0];
        $lat2 = $model->filter()->input('_selector.latitude2') ?? array_keys(ColumnArray::$latitudeArr[$this->board]['select'])[1];
        //额外筛选
        $config = [];
        if (isset(ColumnArray::$latitudeArr[$this->board]['other_select'])) {
            foreach (ColumnArray::$latitudeArr[$this->board]['other_select'] as $k => $v) {
                if ($model->filter()->input('_selector.'.$v['key'])) {
                    $config[$v['key']] = $model->filter()->input('_selector.'.$v['key']);
                }
            }
        }
        # 获取数据源
        $ds = new DataSource();
        $data = $ds->getDataSource($beginDate, $endDate, $this->board, $config);
        if ($data == []) {
            return $model->makePaginator(0, []);
        }

        $rArr = self::dataFilter($data, $this->board, $lat1, $lat2);
        
        // 排序筛选
        if ($model->filter()->input('_sort.column')) {
            $rArr = arraySortTwo($rArr, 'data.'.$model->filter()->input('_sort.column'), $model->filter()->input('_sort.type'));
        }

        // 合计放最底部
        $temp = $rArr['合计'];
        unset($rArr['合计']);
        $rArr['合计'] = $temp;

        $saveData = [];
        if (false && isset(ColumnArray::$latitudeArr[$this->board]['saveData'])) {
            $sd = ColumnArray::$latitudeArr[$this->board]['saveData'];
            $column_map = ColumnArray::$latitudeArr[$this->board]['column'];
            // 表头
            $title = ['latitude' => ''];// 维度
            foreach ($sd as $sdv => $sdk) {
                $title[$sdk] = $column_map[$sdv] ?? '-';
            }
            $saveData[] = $title;
            foreach ($rArr as $l1 => $rarr) {
                $temp = ['latitude' => $l1];
                foreach ($sd as $sdv => $sdk) {
                    $temp[$sdk] = $rarr['data'][$sdv] ?? 0;
                }
                $saveData[] = $temp;
                foreach ($rarr['lat'] as $l2 => $latarr) {
                    $temp2 = ['latitude' => $l2];
                    foreach ($sd as $sdv => $sdk) {
                        $temp2[$sdk] = $latarr['data'][$sdv] ?? 0;
                    }
                    $saveData[] = $temp2;
                }
            }
            $dataObj = [
                'config' => [
                    'beginDate' => $beginDate, 
                    'endDate' => $endDate, 
                    'board' => $this->board, 
                    'config' => $config
                ],
                'data' => $saveData,
            ];
        }
		return $model->makePaginator(count($rArr), $rArr);
	}

    public static function dataFilter($data, $board, $lat1, $lat2)
    {
        $column_arr = ColumnArray::$latitudeArr[$board]['column'];
        $no_detail_arr = ColumnArray::$latitudeArr[$board]['no_detail'] ?? [];
        # 整理结构
        $rArr = [];
        foreach ($data as $k => $v) {
            // if (!isset($v[$lat2])) {
            //     dd($v);
            // }
            // name
            $rArr['合计']['data']['name'] = '合计';
            $rArr['合计']['lat'][$v[$lat2]]['data']['name'] = $v[$lat2];
            $rArr[$v[$lat1]]['data']['name'] = $v[$lat1];
            $rArr[$v[$lat1]]['lat'][$v[$lat2]]['data']['name'] = $v[$lat2];
            // detail
            $rArr['合计']['data']['detail'][] = $v;
            $rArr[$v[$lat1]]['data']['detail'][] = $v;
            $rArr[$v[$lat1]]['lat'][$v[$lat2]]['data']['detail'][] = $v;
            foreach ($column_arr as $ck => $cv) {
                //跳过率
                if (strpos($ck, '/') == true) {
                    continue;
                }
                //是-计数，跳过率，当有/是率
                if (!is_numeric($v[$ck]) && $v[$ck] == '是') {
                    //合计
                    issetAdd($rArr['合计']['data'][$ck], 1);
                    issetAdd($rArr['合计']['lat'][$v[$lat2]]['data'][$ck], 1);
                    if (!in_array($ck, $no_detail_arr)) {
                        $rArr['合计']['data'][$ck.'_detail'][] = $v;
                        $rArr['合计']['lat'][$v[$lat2]]['data'][$ck.'_detail'][] = $v;
                    }
                    //单独维度
                    issetAdd($rArr[$v[$lat1]]['data'][$ck], 1);
                    issetAdd($rArr[$v[$lat1]]['lat'][$v[$lat2]]['data'][$ck], 1);
                    if (!in_array($ck, $no_detail_arr)) {
                        $rArr[$v[$lat1]]['data'][$ck.'_detail'][] = $v;
                        $rArr[$v[$lat1]]['lat'][$v[$lat2]]['data'][$ck.'_detail'][] = $v;
                    }
                }
                //num-统计合计，跳过率，当是数值时
                if (is_numeric($v[$ck]) && $v[$ck] > 0) {
                    //合计
                    issetAdd($rArr['合计']['data'][$ck], $v[$ck]);
                    issetAdd($rArr['合计']['lat'][$v[$lat2]]['data'][$ck], $v[$ck]);
                    if (!in_array($ck, $no_detail_arr)) {
                        $rArr['合计']['data'][$ck.'_detail'][] = $v;
                        $rArr['合计']['lat'][$v[$lat2]]['data'][$ck.'_detail'][] = $v;
                    }
                    //单独维度
                    issetAdd($rArr[$v[$lat1]]['data'][$ck], $v[$ck]);
                    issetAdd($rArr[$v[$lat1]]['lat'][$v[$lat2]]['data'][$ck], $v[$ck]);
                    if (!in_array($ck, $no_detail_arr)) {
                        $rArr[$v[$lat1]]['data'][$ck.'_detail'][] = $v;
                        $rArr[$v[$lat1]]['lat'][$v[$lat2]]['data'][$ck.'_detail'][] = $v;
                    }
                }
            }
        }
        //计算率
        foreach ($rArr as $k => &$v) {
            self::dataRateAvg($column_arr, $v);
            foreach ($v['lat'] as $kk => &$vv) {
                self::dataRateAvg($column_arr, $vv);
            }
        }
        //续减退
        foreach ($rArr as $k => &$v) {
            self::dataSub($column_arr, $v);
            foreach ($v['lat'] as $kk => &$vv) {
                self::dataSub($column_arr, $vv);
            }
        }
        return $rArr;
    }

    /**
     * 计算率或者平均数
     */
    public static function dataRateAvg($column_arr, &$v)
    {
        foreach ($column_arr as $ck => $cv) {
            if (strpos($ck, '/') == true) {
                $rate_arr = explode('/', $ck);
                //如果有avg则求平均数
                if (strpos($rate_arr[1], '_avg') == true) {
                    $a = $v['data'][$rate_arr[0]] ?? 0;//分子
                    $b = $v['data'][str_replace('_avg', '', $rate_arr[1])] ?? 0;//分母
                    $v['data'][$ck] = $b == 0 ? 0 : intval($a/$b);
                } else {
                    $a = $v['data'][$rate_arr[0]] ?? 0;//分子
                    $b = $v['data'][$rate_arr[1]] ?? 0;//分母
                    $v['data'][$ck] = getrate($a, $b);
                }
            }
        }
    }

    /**
     * 计算相减的
     */
    public static function dataSub($column_arr, &$v)
    {
        foreach ($column_arr as $ck => $cv) {
            if (strpos($ck, '-') == true) {
                $rate_arr = explode('-', $ck);
                $a = $v['data'][$rate_arr[0]] ?? 0;
                $b = $v['data'][$rate_arr[1]] ?? 0;
                $v['data'][$ck] = $a - $b;
            }
        }
    }
}
